var collection_servlet ;
var views_servlet;

var commentMaxLength = 500;
var entityNameMaxLength = 50;
var viewNameNavMaxLength = 28;
var recommendMaxLength = 5;
var count ;

$(document).ready(function(){
	count = eval($("#count").val()) ;
	views_servlet = WEBAPP+"views";
	collection_servlet = WEBAPP+"collection";
	displayLang = $("#display-lang").val();//must be the name "displayLang" (for fetchValues)
	entityType = $("#etype").val();
	entityID = $("#eid").val();
	Genre = $("#genre").val();
	checkContentLengthWithMoreLess($(".comment-box"),commentMaxLength);
    /*start:customization buttons*/
    $(".custom_op").click(function(){
    	$(".smenu").hide();
    	hideGlobalSettingMenu();
    	
    	$("#emenu").toggle();
    });

    /*start:显示数据源*/
	   $("#listView .view-ds").live("click",function(){
		   //show the datasource panel
		   var context = $("#listView .vcontent").children(".relative");
		   context.find(".dsBox").remove();
		   var dsBox = $("<div class='dsBox'></div>");
		   context.append(dsBox);
		   var close = $("<a class='cls_ds'></a>").appendTo(dsBox);
		   close.attr("title","Hide datasources");
		   if(displayLang=="zh")
			   close.attr("title","隐藏数据源");
		   close.bind("click",function(){
			   dsBox.remove();
		   });
		   
		   var explore = $("<a class='exp_ds'></a>").appendTo(dsBox);
		   explore.attr("title","Browse datasources");
		   if(displayLang=="zh")
			   explore.attr("title","浏览数据源");
		   explore.bind("click",function(){
			   var str="";
			   dsBox.find(".ds>a").each(function(){
				  var ds_id = $(this).attr("dsid");
				  str=str+ds_id+"_";
			   });
			   str =str.substring(0,str.length-1);
			   var location = TMP_DS_LOCATION+str;
			   location = location+"?lang="+displayLang;
			   window.location = location;
			   
		   });
		   
		   var dsTitle = $("<div class='dstitle'></div>").appendTo(dsBox);
		   if(displayLang=="en"){
			   dsTitle.html("Datasources");
		   }else if(displayLang=="zh"){
			   dsTitle.html("数据源");
		   }
		   var dsItems = $("<div class='dsItems'></div>").appendTo(dsBox);
		   context.find(".datasource .ds").each(function(){
			  var dsid = $(this).find("a").attr("dsid");
			  if(dsBox.find("a[dsid="+dsid+"]").length>0){
				  return;
			  }
			  $(this).clone().appendTo(dsItems);
		   });
		   
		   scrollTop(dsBox);
	   });
	   
	   $("#tableView .view-ds").live("click",function(){
		   //show the datasource panel
		   var context = $("#tableView .vcontent").children(".relative");
		   context.find(".dsBox").remove();
		   var dsBox = $("<div class='dsBox'></div>");
		   context.append(dsBox);
		   var close = $("<a class='cls_ds'></a>").appendTo(dsBox);
		   close.attr("title","Hide datasources");
		   if(displayLang=="zh")
			   close.attr("title","隐藏数据源");
		   close.bind("click",function(){
			   dsBox.remove();
		   });
		   
		   var explore = $("<a class='exp_ds'></a>").appendTo(dsBox);
		   explore.attr("title","Browse datasources");
		   if(displayLang=="zh")
			   explore.attr("title","浏览数据源");
		   explore.bind("click",function(){
			   var str="";
			   dsBox.find(".ds>a").each(function(){
				  var ds_id = $(this).attr("dsid");
				  str=str+ds_id+"_";
			   });
			   str =str.substring(0,str.length-1);
			   alert(str);
			   var location = TMP_DS_LOCATION+str;
			   location = location+"?lang="+displayLang;
			   window.location = location;
			   
		   });
		   
		   var dsTitle = $("<div class='dstitle'></div>").appendTo(dsBox);
		   if(displayLang=="en"){
			   dsTitle.html("Datasources");
		   }else if(displayLang=="zh"){
			   dsTitle.html("数据源");
		   }
		   var dsItems = $("<div class='dsItems'></div>").appendTo(dsBox);
		   context.find(".datasource .ds").each(function(){
			  var dsid = $(this).find("a").attr("dsid");
			  if(dsBox.find("a[dsid="+dsid+"]").length>0){
				  return;
			  }
			  $(this).clone().appendTo(dsItems);
		   });
		   
		   scrollTop(dsBox);
	   });
    /*end:显示数据源*/
    
    $(".rmFilter").live("click",function(){
    	var filterID  = $(this).parent().attr("mid");
    	if($(this).parent().find(".filterInUse").attr("checked")){
    		if(displayLang=="en")
				$(".memberList").html("Filtering...");
		   else if(displayLang=="zh")
				$(".memberList").html("过滤中...");
		   var div = $("<div class='loading2'></div>").appendTo($(".memberList"));
		   disableFilter(filterID);
    	}
    	
    	$(this).parent().remove();
    	$(".collectionMembers").find("div[fid="+filterID+"]").remove();
    });
    
    $("span.constraint a").live("click",function(){
    	 //check the checkbox
    	var targetCheckbox = $(this).parent().parent().parent().find("input[type=checkbox]");
    	
    	var filterDMName = $(this).parent().parent().find(".filterdmname").html();
    	var filterItem = $(this).parent().parent().parent().parent().parent();
    	var dmtype = filterItem.attr("dmtype");
    	var dmid  = filterItem.attr("dmid");
    	var inverse = filterItem.attr("inverse");
    	var vtype = filterItem.attr("vtype");
    	var mid = filterItem.attr("mid");
    	
    	var filterDialog = $(".fdialog").html("");
    	var nameDiv = $("<div class='fname'></div>").html(filterDMName);
    	filterDialog.append(nameDiv);
    	var tabArray = new Array();
    	if(dmtype!=ORIGIN_DMTYPE||dmid!=RDF_TYPE_URI_ID){
    	    var opDiv = $("<div class='opBox'></div>");
    	    opDiv.appendTo(filterDialog);
    	    var titlespan=$("<span class='ftitle'></span>");
    	    if(displayLang=="en")
    		    titlespan.html("value");
    	    else if(displayLang=="zh")
    		    titlespan.html("取值");
    	    opDiv.append(titlespan);
    		var select = $("<select></select>").appendTo(opDiv);
        	var equalOption = $("<option class='equalop' mtab_target='equal'></option>").appendTo(select);
        	if(displayLang=="en")
        		equalOption.html("equal");
        	else if(displayLang=="zh")
        		equalOption.html("等于");
        	if(vtype==URI_VTYPE){
        		var classOption = $("<option class='valueclassop' mtab_target='valueclass'></option>").appendTo(select);
        		if(displayLang=="en")
        			classOption.html("has type");
        		else if(displayLang=="zh")
        			classOption.html("类型");
        	}
        	//bind events
        	select.bind("change",function(){
        		var valueDiv =$(this).parent().parent().find(".vbox");
    			valueDiv.find(".mtab_content.active").removeClass("active");
        		if($(this).find("option:selected").hasClass("valueclassop")){
        			var container = valueDiv.find(".mtab_content[mtab_id=valueclass]");
        			container.addClass("active");
        			if(!container.hasClass("inited")){
        				valueClassConstraint(container,dmtype,dmid,inverse);
        			}
        		}else if($(this).find("option:selected").hasClass("equalop")){
        			var container = valueDiv.find(".mtab_content[mtab_id=equal]");
        			container.addClass("active");
        			if(!container.hasClass("inited")){
        				valueEqualConstraint(container,dmtype,dmid,inverse);
        			}
        		}
        	});
        	tabArray.push("equal");
        	tabArray.push("valueclass");
    	}else{
    		tabArray.push("class");
    	}
    	var title;
    	if(displayLang=="en"){
    		title="Value Constraint";
    	}else if(displayLang=="zh"){
    		title="取值约束";
    	}
    	var valueDiv = $("<div class='vbox'></div>").appendTo(filterDialog);
    	for(i=0;i<tabArray.length;i++){
    		var tab_content = $("<div class='mtab_content'></div>").appendTo(valueDiv);
    		tab_content.attr("mtab_id",tabArray[i]);
    	}
    	
    	var buttonJSON = new Object();
    	var buttonTitle ;
    	if(displayLang=="en"){
    		buttonTitle = "Done";
    	}else if(displayLang=="zh"){
    		buttonTitle="完成";
    	}
    	buttonJSON[buttonTitle] =function(){
			filterDialog.dialog("close");
			var opDiv = filterDialog.find(".opBox");
	        if(opDiv.length>0){
	        	var soption = opDiv.find("option:selected");
	        	if(soption.hasClass("equalop")){
	        		var checkbox = valueDiv.find(".equalChkbox:checked");
	        		if(checkbox.length>0){
	        			var li = checkbox.parent();
	        			if(displayLang=="en"){
        					filterItem.find(".constraint").html("has value(s)");
        				}else if(displayLang=="zh"){
        					filterItem.find(".constraint").html("拥有取值");
        				}
	        			var filterDetail = filterItem.find(".filterDetail");
	        			var constDiv = $("<div class='fvconst'></div>").appendTo(filterDetail);
	        			var ul = $("<ul class='pvalue'></ul>").appendTo(constDiv);
	        			valueDiv.find(".equalChkbox:checked").each(function(){
	        				$(this).parent().clone().appendTo(ul);
	        			});
	        			ul.find("input[type=checkbox]").remove();
	        			addEqualFilter(mid);
	        			
	        			//check the checkbox of filter if not checked
	        			targetCheckbox.attr("checked","checked");
	        		}
	        	}else if(soption.hasClass("valueclassop")){
	        		var checkedLis = valueDiv.find(".tree").jstree("get_checked",null,false);
	        		if(checkedLis.length>0){
	        			if(!valueDiv.find(".tree").jstree("is_checked",$("#-1"))){
	        				filterItem.find(".constraint").html("has value(s) of type");
	        				if(displayLang=="zh"){
	        					filterItem.find(".constraint").html("取值拥有类型");
	        				}
	        				var filterDetail = filterItem.find(".filterDetail");
	        				var constDiv = $("<div class='fvconst'></div>").appendTo(filterDetail);
	        				var ul = $("<ul class='pvalue'></ul>").appendTo(constDiv);
	        				checkedLis.each(function(){
	        					var li = $("<li></li>").appendTo(ul);
	        					li.attr("class_set",$(this).attr("class_set"));
	        					li.attr("id",$(this).attr("id"));
	        					var a = $(this).find("a").addClass("vlink");
	        					a.find("ins").remove();
	        					li.append(a);
	        				});
	        				addValueClassFilter(mid);
	        				//check the checkbox of filter if not checked
		        			targetCheckbox.attr("checked","checked");
	        			}
	        		}
	        	}
	        }else{
	        	//表明对当前集合成员的类层次结构进行过滤
        		var checkedLis = valueDiv.find(".tree").jstree("get_checked",null,false);
        		if(checkedLis.length>0){
        			if(!valueDiv.find(".tree").jstree("is_checked",$("#-1"))){
        				filterItem.find(".constraint").html("");
        				var filterDetail = filterItem.find(".filterDetail");
        				var constDiv = $("<div class='fvconst'></div>").appendTo(filterDetail);
        				var ul = $("<ul class='pvalue'></ul>").appendTo(constDiv);
        				checkedLis.each(function(){
        					var li = $("<li></li>").appendTo(ul);
        					li.attr("class_set",$(this).attr("class_set"));
        					li.attr("id",$(this).attr("id"));
        					var a = $(this).find("a").addClass("vlink");
        					a.find("ins").remove();
        					li.append(a);
        				});
        				addFilterMemberClass(mid);
        			}
        		}
	        }
			return false;	
	   };
      	filterDialog.dialog({
    		modal:true,
    		title:title,
    		width:500,
    	    height:500,
    		buttons:buttonJSON
    	});
    	//init valueDiv
    	if(dmtype==ORIGIN_DMTYPE && dmid==RDF_TYPE_URI_ID){
    		var box = valueDiv.find(".mtab_content[mtab_id=class]");
    		box.addClass("active");
    		memberClassConstraint(box);
    	}else{
    		var box = valueDiv.find(".mtab_content[mtab_id=equal]");
    		box.addClass("active");
    		valueEqualConstraint(box,dmtype,dmid,inverse);
    	}
    });
    
    init();
	
	/*start:slide images*/
    $(".carousel").mouseover(function(){
    	if($(".next").length>0){
    		$(".next").show();
    		$(".prev").show();
    	}
    });
    
    $(".carousel").mouseout(function(){
    	if($(".next").length>0){
    		$(".next").hide();
    		$(".prev").hide();
    	}
    });
    
    $(".carousel").jCarouselLite({
    	btnNext: ".next",
    	btnPrev: ".prev",
    	visible: 1,		
    	speed: 500,	
    	scroll: 1	
    });
    /*end:slide images*/
    
    $(".mytab a").click(function(e){
    	e.preventDefault();
        $(this).tab("show");
        if($(this).parent().hasClass("views")){
        	var active = $(".mypill>li.active");
        	if($(active).hasClass("inited") && $(active).attr("refresh")=="0")
             	  return;
           if(!$(active).hasClass("inited")) {
      		   initViewOnTabClick($(active).find("a"));
      	   }else{
      		   updateViewOnTabClick($(active).find("a"));
      	   }
      	   
        }
    });
    
    $(".mypill a").click(function(e){
       e.preventDefault();
       $(this).tab("show");
       if($(this).parent().hasClass("inited") && $(this).parent().attr("refresh")=="0")
       	  return;
	   if(!$(this).parent().hasClass("inited")) {
		   initViewOnTabClick(this);
	   }else{
		   updateViewOnTabClick(this);
	   }
	   
    });

/*start:recommend entity*/
	getRecommends(Genre,entityID,displayLang, recommendMaxLength);
	$(".recomdList li" ).live("mouseover",function(event){
       $(this).addClass("bh");
	});
	
	$(".recomdList li" ).live("mouseout",function(){
		$(this).removeClass("bh");
	});
	$(".recomdList li" ).live("click",function(){
		window.location = $(this).children("a").attr("loc");
	});
/*end:recommend entity*/

/*start:view set operation*/
	$(".vset" ).live("click",function(event){
        var target =  $(this).parent().find('.smenu');
        target.toggle();
        
        event.stopPropagation();
	});
	
	$(".vset" ).live("mousedown",function(){
        $(this).addClass("ui-state-hover");
	});
	
	$(".vset" ).live("mouseup",function(){
        $(this).removeClass("ui-state-hover");
	});
/*end:view end operation*/
	
	/*bookmark*/
	$(".bmwarn_op").live("mouseover",function(){
		$(this).addClass("wbh");
	});
	
	$(".bmwarn_op").live("mouseout",function(){
		$(this).removeClass("wbh");
	});
	
	var buttonJSON;
	if(displayLang=="en")
		 buttonJSON = {
				"Done":function(){
				    if(nameCheck($("#bookmarkName"))){
				    	var bmname = $("#bookmarkName").val().trim();
				    	var flag = existBookmark(bmname,getUser(),displayLang,entityType,entityID);
				    	if(!flag){
				    		saveBookmark(bmname,getUser(),displayLang,entityType,entityID);
				    	}else{
				    		$("#warning-op").dialog({
				    			modal:true,
				    			width:350
				    		});
				    		
				    		$(".bmwarn_op.ov").unbind("click");
				    		$(".bmwarn_op.ov").bind("click",function(){
				    			saveBookmark(bmname,getUser(),displayLang,entityType,entityID);
				    			$("#warning-op").dialog("close");
				    		});
				    		
				    		$(".bmwarn_op.cancel").unbind("click");
				    		$(".bmwarn_op.cancel").bind("click",function(){
				    			$("#warning-op").dialog("close");
				    		});
				    	}
				    	$("#bookmark-op").dialog("close");
				    }
					return false;	
			   }
	    };
	else if(displayLang=="zh")
		buttonJSON = {
			"完成":function(){
				if(nameCheck($("#bookmarkName"))){
			    	var bmname = $("#bookmarkName").val().trim();
			    	var flag = existBookmark(bmname,getUser(),displayLang,entityType,entityID);
			    	if(!flag){
			    		saveBookmark(bmname,getUser(),displayLang,entityType,entityID);
			    	}else{
			    		$("#warning-op").dialog({
			    			modal:true,
			    			width:350
			    		});
			    		
			    		$(".bmwarn_op.ov").unbind("click");
			    		$(".bmwarn_op.ov").bind("click",function(){
			    			saveBookmark(bmname,getUser(),displayLang,entityType,entityID);
			    			$("#warning-op").dialog("close");
			    		});
			    		
			    		$(".bmwarn_op.cancel").unbind("click");
			    		$(".bmwarn_op.cancel").bind("click",function(){
			    			$("#warning-op").dialog("close");
			    		});
			    	}
			    	$("#bookmark-op").dialog("close");
			    }
				return false;	
		   }
        };
	$("a.bookmark_op").click(function(){
		$("textarea").val("");
		$("#bookmark-op").dialog({
			 modal:true,
			 width:350,
			 buttons:buttonJSON
		});
		return false;		
	});
	
	/*input hints*/
	$(".ftext").focus(function(){
		$(this).css("border-color","#256EB1");
		$(this).parent().find(".errorMsg").hide();
	});
	
	/*comment*/
	$("a.more-content").live("click",function(){
		var html = $(this).parent().find(".hidden").html();
		var parent = $(this).parent();
		parent.html(html);
		var less = $("<a class='less-content'>Less</a>");
		$(parent).append(less);
	});
	
	$("a.less-content").live("click",function(){
		var parent=$(this).parent();
		$(this).parent().find("a.less-content").remove();
		checkContentLengthWithMoreLess(parent,commentMaxLength);
	});
	
	$("a.entity_edit").click(function(){
	     var members = getCurrentMembers();
	     var curMemCID =  constructCollectionOfCurrentMembers(members);
		 var url = window.location.href;
  		 var location = WEBAPP+"views/construct_collection.jsp?genre="+Genre+"&eid="+entityID+"&curmemcid="+curMemCID;
  		 var name = $(".entity-label").html();
  		 name = encodeURIComponent(encodeURIComponent(name));
  		 location = location +"&n="+name;
  		 if(displayLang=="zh"){
  		    location =  location+"&lang=zh" ;
  		 }
  		 window.location = location;
	});
	
	$("a.entity_new").click(function(){
	     var members = getCurrentMembers();
	     var curMemCID =  constructCollectionOfCurrentMembers(members);
		 var url = window.location.href;
 		 var location = WEBAPP+"views/construct_collection.jsp?genre="+Genre+"&eid="+entityID+"&curmemcid="+curMemCID;
 		 var name = $(".entity-label").html();
 		 name = encodeURIComponent(encodeURIComponent(name));
 		 location = location +"&n="+name;
 		 if(displayLang=="zh"){
 		    location =  location+"&lang=zh" ;
 		 }
 		 window.location = location;
	});
	
	/*left nav*/
	   $(".dmenu li").live("mouseover",function(){
		   if(!$(this).hasClass("mspacingLittle")){
			   $(this).addClass("ah");
		   }
	   });
	   $(".dmenu li").live("mouseout",function(){
		   $(this).removeClass("ah");
	   });
	   
	   /* start:right panel*/
	   $(".pvalue li").live("mouseover",function(){
		   $(this).addClass("bh");
	   });
	   $(".pvalue li").live("mouseout",function(){
		   $(this).removeClass("bh");
	   });	   
	   $("td li.value" ).live("mouseover",function(event){
	       $(this).addClass("bh");
		});
		
		$("td li.value" ).live("mouseout",function(){
			$(this).removeClass("bh");
		});
		$(".moreV").live("click",function(){
			$(this).siblings("li").show();
			$(this).siblings(".lessV").show();
			$(this).hide();
		});
		$(".lessV").live("click",function(){
			$(this).siblings("li:first").nextAll().hide();
			$(this).siblings(".moreV").show();
			$(this).hide();
		});
	   /**titlebar**/
	   $(".titlebar").live("click",function(){
		   $(this).find(".status").toggleClass("collapse");
		   $(this).parent().find(".content").toggle('fast');
	   });
	   
	   //list view
	   $("a.cmem_num_box").live("click",function(){
		   var title;
		   if(displayLang=="en"){
			   title = "Members have this value";
		   }else if(displayLang=="zh"){
			   title=  "拥有该取值的成员";
		   }
		   var target = $(this).parent();
		   $(this).parent().find(".memDiv").clone().dialog({
   			  width:500,
   			  title:title,
   			  modal:true,
   			  open:function(){
   				  target.addClass("selectedHighlight");
   			  },
   			  close:function(){
   				 target.removeClass("selectedHighlight");
   			  }
   		   });
	   });
	   
	   /*end: right panel*/
	   
	   
	   /***explore***/
	   $("span.explore").live("mouseover",function(){
		   $(this).addClass("hover");
	   });
	   
	   $("span.explore").live("mouseout",function(){
		   $(this).removeClass("hover");
	   });
	   
	   $("span.explore").live("click",function(event){
		   event.stopPropagation(); 
		   var collection = new Array();
		   $(this).parent().parent().find(".content .pvalue>li").each(function(){
			   var etype = $(this).attr("etype");
			   if(etype=="l")
				   return;
			   var eid = $(this).attr("eid");
			   var object = {"etype":etype,"eid":eid};
			   collection.push(object);
		   });
		   var entityLabel = $('.entity-label').html();
		   var dmtitle= $(this).parent().find(".title").html();
		   var name = entityLabel+"."+dmtitle;
		   browseCollection(collection,name);
	   });
	   
	   /*remve query item in list view*/
	   $("a.close").live("click",function(event){
			$(this).parent().parent().remove();
			event.stopPropagation();
			
			//remove old datasources
			var context = $("#listView .vcontent").children(".relative");
			context.find(".dsBox").remove();
		});
	   
	   /*start:filter*/
	   $(".filterInUse").live("change",function(){
		  var filterID = $(this).parent().parent().parent().attr("mid");
		  if($(this).attr("checked")){
			  //选中意味着原来没有
			  var curMems = getCurrentMembers();
			  if(displayLang=="en")
				$(".memberList").html("Filtering...");
			  else if(displayLang=="zh")
				$(".memberList").html("过滤中...");
			  var div = $("<div class='loading2'></div>").appendTo($(".memberList"));
			  enableFilter(filterID,curMems);
			  
		  }else{
			  //不选中意味着删除
			  if(displayLang=="en")
					$(".memberList").html("Filtering...");
			  else if(displayLang=="zh")
					$(".memberList").html("过滤中...");
			  var div = $("<div class='loading2'></div>").appendTo($(".memberList"));
			  disableFilter(filterID);
		  }
	   });
	   /*end:filter*/
	   
});

function getRecommends(type_str, id, lang,length){
//	alert(type_int+"|"+id+"|"+lang);
	var data = {};
	data["type_str"]=type_str+"";
	data["id"]=id+"";
	data["lang"]=lang;
	data["length"]=length;
	data = JSON.stringify(data);
//	alert(data+"|"+WEBAPP+"recommendServlet");
	data = ("getRecommends="+encodeURIComponent(data));
	$.ajax({
		url: WEBAPP+"recommendServlet",
		data: data,
		async: true,
		dataType: 'text',//for chinese messy code //'json',
		type: 'post',
		beforeSend:function(){
			var container = $(".recommend-box");
			$(container).html("");
			$(container).addClass("loading2");
		},
		success: function(result_str){
			var result_text = decodeURIComponent(result_str);
			var result = eval("("+result_text+")");
			var container = $(".recommend-box");
			$(container).removeClass("loading2");
			var lang = $("#display-lang").val();
			if(result==null || result.status!="ok"){
				return;
			}else{
//				$(container).html("");
				var relArray = result["byRelated"];
				if(relArray != null && relArray.length>0){
					var title = "Related collection";
					if(lang=="zh"){
						title = "相关集合";
					}
					buildRecommendBox(container, relArray, title);
				}//end of if_relArray
				
				var histArray = result["byHistory"];
				if(histArray != null && histArray.length>0){
					var title = "People also visited";
					if(lang=="zh"){
						title = "人们还访问过";
					}
					buildRecommendBox(container, histArray, title);
				}//end of if_hisArray
				
			}
			
		}
	});
}
function buildRecommendBox(container, array, title){
	if(array == null || $(container).length<=0){
		return;
	}
	var relBox = $("<div class='log-rcmdbox'></div>");
	var titleDiv = $("<div class='rcmd-title'></div>");
	$(titleDiv).text(title);
	$(relBox).append(titleDiv);
	var contentBox = $("<div class='contentBox'></div>");
	$(relBox).append(contentBox);
	var listUl = $("<ul class='recomdList'></ul>");
	$(relBox).append(listUl);
	$(container).append(relBox);
	for(var i=0; i<array.length; i++){
		var item = array[i];
		var id = item["id"];
		var genre = item["genre"];
		var name = item["name"];
		var li = $("<li></li>");
		var a = $("<a></a>");
		$(a).text(name);

		if($(listUl).find("li[eid="+eid+"]").length>0){
			if($(listUl).find("li[eid="+eid+"]").find("a").html().trim()==name){
				   continue;
			}
		 }
		
		var href =WEBAPP+"entity/";
		var eid;
		if(genre==COLLECTION_NO){
			href=href+COLLECTION_STR;
			eid=COLLECTION_STR ;
		}else if(genre==CUSTOM_ENTITY_NO){
			href = href+CUSTOM_ENTITY_STR;
			eid=CUSTOM_ENTITY_STR ;
		}else if(genre==URI_ENTITY_NO){
			href= href+URI_ENTITY_STR ;
			eid=URI_ENTITY_STR ;
		}
		href =href+id;
		eid = eid + id;

		$(li).attr("eid",eid);
		$(listUl).append(li);
		
		if(displayLang=="zh"){
			href = href+"?lang=zh" ;
		}
		a.attr("loc",href) ;
		$(li).append(a);
	}
}

function blurState(e){
	$(e).css("border-color","#BDC7D8");
}

function browseCollection(collection,name){
	 var data={};
	 data["lang"] = displayLang;
	 data["collection"] = collection;
	 data["name"] = name;
    data =  JSON.stringify(data);
    data =("tmpcollection="+encodeURIComponent(data));
    $.ajax({
 	   url:"/sview/collection",
 	   async:true,
 	   data:data,
 	   dataType:"text",
 	   type:"post" ,
 	   success:function(collectionID){
 		  var location = "/sview/entity/c"+collectionID;
 		  location = location+"?lang="+displayLang;
 		  window.location = location;
 	   }
    });
}

function constructCollectionOfCurrentMembers(collection){
   var result;
   var data={};
   data["lang"] = displayLang;
   data["collection"] = collection;
   data =  JSON.stringify(data);
   data =("tmpcollection="+encodeURIComponent(data));
   $.ajax({
	   url:"/sview/collection",
	   async:false,
	   data:data,
	   dataType:"text",
	   type:"post" ,
	   success:function(collectionID){
		 result = collectionID;
	   }
   });
   return result;
}

function browseCollection(collection,name){
	 var data={};
	 data["lang"] = displayLang;
	 data["collection"] = collection;
	 data["name"] = name;
     data =  JSON.stringify(data);
     data =("tmpcollection="+encodeURIComponent(data));
     $.ajax({
  	   url:"/sview/collection",
  	   async:true,
  	   data:data,
  	   dataType:"text",
  	   type:"post" ,
  	   success:function(collectionID){
  		  var location = "/sview/entity/c"+collectionID;
  		  location = location+"?lang="+displayLang;
  		  window.location = location;
  	   }
     });
}

function checkAuthority(vid){
	 var array = new Array() ;
	 var data={};
	 data["viewID"] = vid;
	 var user = getUser();
	 data["user"] = user;
     data =  JSON.stringify(data);
     data =("checkAuthor="+encodeURIComponent(data));
     $.ajax({
 	  url:views_servlet,
 	  async:false,
 	  data:data,
 	  dataType:"json",
 	  type:"post",
      success:function(res){  
    	  var hasAuthor = res["hasAuthor"];
    	  var gid = res["gid"];
    	  var isTrans = res["isTranslatedView"];
    	  if(hasAuthor=="yes"){
    		  array.push(true);
    	  }else
    		  array.push(false);
    	  array.push(gid);
    	  array.push(isTrans);
    	  if(isTrans==true){
    		  array.push(res["srcvid"]);
    	  }
      }
     });
    
     return array ;
}

/**
 * 得到当前集合的成员
 */
function getCurrentMembers(){
	var array = new Array();
	$(".memberList>li").each(function(){
		var etype = $(this).attr('etype');
	    var eid = $(this).attr("eid");
	    var obj = {"etype":etype,"eid":eid};
	    array.push(obj);
	});
	return array;
}
/*
 * add by lqx for tableView
 */
function getCurrentMembersWithName(){
	var array = new Array();
	$(".memberList>li").each(function(){
		var etype = $(this).attr('etype');
	    var eid = $(this).attr("eid");
	    var ename = $(this).find(".mem-entity-label").attr("title");
	    var obj = {"etype":etype,"eid":eid,"ename":ename};
	    array.push(obj);
	});
	return array;
}
function getDisplayLang(){
	var displayLang = $("#display-lang").val();
	return displayLang;
}

function getMID(){
    count = count+1;
    return count-1;
}

function getTypes(){
	var array =new Array();
	$(".entity-type .type").each(function(){
		 $(this).find("span").each(function(){
			 var tid = $(this).attr("type_id");
			 array.push(tid); 
		 });
	});
	return array;
}

/**
 * get only min class id of the view which may be innerclass
 * @returns {Array} first:isInner,second:classID
 */
function getMinType(){
	var array = new Array();
    if($("#minTypes").length>0){
    	var ele = $("#minTypes");
    	array.push(ele.attr("inner"));
    	array.push(ele.attr("cid"));
    }
	return array;
}

function getTypeSelected(){
	var tid = $(".ts option:selected").attr("tid");
	return tid;
}

function isInnerClass(){
	var ttype = $(".ts option:selected").attr("ttype");
	if(ttype=="i")
		return true;
	return false;
}

function getListViewDatamember(ul){
	 var data={};
	 var eid = parseInt(entityID);
	 data["collectionID"] = eid;
	 data["lang"] = displayLang;
	 var minTypeArray = getMinType();
	 var isInner = minTypeArray[0] ;
	 var classID = minTypeArray[1] ;
	 data["classID"] = classID;
	 data["isInner"]=isInner;
     data =  JSON.stringify(data);
     data =("initViewDMList="+encodeURIComponent(data));
     $.ajax({
 	  url:collection_servlet,
 	  async:true,
 	  data:data,
 	  dataType:"json",
 	  type:"post",
 	  beforeSend:function(){
		  $(ul).addClass("loading2");
	  },
      success:function(res){
    	  $(ul).removeClass("loading2");
       	  
    	  var result = res["list"];
    	  var dmids = new Array();
    	  var dmtypes =new Array();
    	  var inverses = new Array();
    	  for(i=0;i<result.length;i++){
    		  var item=result[i];
    		  var dmtype = item["dmtype"];
    		  var dmid = item["dmid"];
    		  dmids.push(dmid);
    		  dmtypes.push(dmtype);
    		  var name = item["name"];
    		  var inverse  = item["inverse"] ;
    		  inverses.push(inverse);
    		  var li = $('<li class="prop"></li>');
    		  ul.append(li);
    		  li.attr("dmid",dmid);
    		  li.attr("dmtype",dmtype);
    		  li.attr("inverse",inverse);
    		  
    		  var titlebar = $("<div class='titlebar'></div>");
    		  li.append(titlebar);
    		  var spanLoading = $("<span class='loading'></span>");
    		  titlebar.append(spanLoading);
    		  var spanTitle = $("<span class='title'></span>");
    		  spanTitle.text(name);
    		  var status = $('<a class="status"></a>');
    		  titlebar.append(status);
    		  titlebar.append(spanTitle);
    	
    		  var closeSpan = $("<a class='close'></a>");
    		  if(displayLang=="en"){
    			  closeSpan.attr("title","Remove");
    		  }else if(displayLang=="zh"){
    			  closeSpan.attr("title","移除") ; 
    		  }
    		  titlebar.append(closeSpan);
    		  var content = $("<div class='content'></div>");
    		  var pvalue = $("<ul class='pvalue'></ul>");
    		  pvalue.attr("dmtype",dmtype);
    		  pvalue.attr("dmid",dmid);
    		  li.append(content) ;
    		  content.append(pvalue);
    	  }
    	  
    	  /*must be out of the above loop*/
    	  for(i=0;i<dmids.length;i++){
    		  var dmid = dmids[i];
    		  var dmtype = dmtypes[i];
    		  var inverse = inverses[i];
    		  var container = ul.find("li[dmid="+dmid+"][dmtype="+dmtype+"][inverse="+inverse+"]").find(".pvalue");
    		  var status = "undownloaded" ;
    		  var members = getCurrentMembers();
    		  fetchValuesInCollectionBrowsing("list",displayLang,container,dmtype,dmid,inverse,members,status);
    	  }
      }
   });
}

function updateListViewDatamemberValues(ul){
	ul.find("li.prop").each(function(){
		 var dmid = $(this).attr("dmid");
		 var dmtype = $(this).attr("dmtype");
		 var inverse =  $(this).attr("inverse");
		 var container = $(this).find(".pvalue").html("");
		 var status = "undownloaded" ;
		 var members = getCurrentMembers();
		 updateValuesInCollectionBrowsing("list",displayLang,container,dmtype,dmid,inverse,members,status);
	});
}


function updateTableViewDatamemberValues(container){
	$(container).html("");
	var relativeDiv= $("<div class='relative'></div>");
	container.append(relativeDiv);
	
	//add set button
	var vsectSpan = $('<span class="vsetc"><button class="vset ui-button ui-widget ui-state-default ui-corner-all ui-button-icons-only"  > <span class="icon-gear"></span><span class="icon-triangle-1-s"></span></button></span>');
	var menuDiv= null;
	if(displayLang=='en')
		menuDiv =$('<div class="dmenu smenu" ><ol><li><a href="javascript:void(0)" class="view-ds">Show datasources</a></li></ol></div>');
	else if(displayLang=='zh')
		menuDiv =$('<div class="dmenu smenu" ><ol><li><a href="javascript:void(0)" class="view-ds">显示数据源</a></li></ol></div>');
	vsectSpan.append(menuDiv);
	var setDiv = $("<div class='setDiv'></div>");
	setDiv.append(vsectSpan.clone());
	relativeDiv.append(setDiv);
	
	var tableDiv = $("<div id='dmTable'></div>");
	relativeDiv.append(tableDiv);
	var thead = $("<thead></thead>");
	tableDiv.html(thead);
	var tbody = $("<tbody></tbody>");
	tableDiv.append(tbody);
	getTableViewDatamember(tableDiv,"update");
}

function addFilter(ul,dmtype,dmid,inverse,name,vtype){
	var mid = getMID();
	var li = $('<li class="filterItem"></li>');
	li.attr("mid",mid);
	ul.append(li);
	li.attr("dmid", dmid);
	li.attr("dmtype", dmtype);
	li.attr("inverse", inverse);
	li.attr("vtype", vtype);
	
	var removeOp = $("<a href='javascript:void(0)' class='rmFilter'></a>").appendTo(li);
    if(displayLang=="en"){
    	removeOp.attr("title","Delete this filter");
    }else  if(displayLang=="zh"){
    	removeOp.attr("title","删除这个过滤器");
    }
	
	var filterBox = $("<div class='filterDetail'></div>");
	li.append(filterBox);
	var filterDM = $("<div class='filterdm'></div>").appendTo(filterBox);
	var box = $("<input type='checkbox' name='filterInUse' checked class='filterInUse'/>");
	if(displayLang=="en"){
		box.attr("title","Enable this filter");
    }else  if(displayLang=="zh"){
    	box.attr("title","删除这个过滤器");
    }

	filterDM.append(box);
	var filterDesc = $("<span></span>").appendTo(filterDM);
	var dmnameSpan = $("<span class='filterdmname'></span>").html(name).appendTo(filterDesc);
	var dmconstraint = $("<span class='constraint'><a href='javascript:void(0)'></a></span>").appendTo(filterDesc);
	if(displayLang=='en'){
		dmconstraint.find("a").html("add value contraint");
	}else if(displayLang=='zh'){
		dmconstraint.find("a").html("添加取值约束");
	}
	
	filterMembersByAdd(dmtype,dmid,inverse,mid);
}

/**
 * 过滤出特定类型的实体
 * @param filterID
 */
function addFilterMemberClass(filterID){
	//改变mid，删除结果
	$(".collectionMembers").find(".filter[fid="+filterID+"]").remove();
	var originFilter = $(".filterList").find(".filterItem[mid="+filterID+"]");
	var newMID = getMID();
	originFilter.attr("mid",newMID);
	var dmtype = originFilter.attr("dmtype");
	var dmid = originFilter.attr("dmid");
	var inverse = originFilter.attr("inverse");
	var carray = new Array();
	originFilter.find(".fvconst .pvalue>li").each(function(){
		var class_set = $(this).attr("class_set");
		carray.push(class_set);
	});
	//对现有的重新约束
	var etype = entityType;
	var eid = entityID ;
	var container = $("<div class='filter'></div>");
	container.attr("fid",newMID);
	container.appendTo(".collectionMembers");
	
	var curMems = getCurrentMembers();
	if(displayLang=="en")
		$(".memberList").html("Filtering...");
	else if(displayLang=="zh")
		$(".memberList").html("过滤中...");
	var div = $("<div class='loading2'></div>").appendTo($(".memberList"));
	getMemberClassFilterResult(container,displayLang,dmtype,dmid,inverse,etype,eid,carray);
	
	enableFilter(newMID,curMems);
}

function addEqualFilter(filterID){
	//改变mid，删除结果
	$(".collectionMembers").find(".filter[fid="+filterID+"]").remove();
	var originFilter = $(".filterList").find(".filterItem[mid="+filterID+"]");
	var newMID = getMID();
	originFilter.attr("mid",newMID);
	var dmtype = originFilter.attr("dmtype");
	var dmid = originFilter.attr("dmid");
	var inverse = originFilter.attr("inverse");
	var varray = new Array();
	originFilter.find(".fvconst .pvalue>li").each(function(){
		var etype = $(this).attr("etype");
		var eid = $(this).attr("eid");
		var label = "";
		var literalLang="";
		var literalType = "-1";
		if(etype=="l"){
		  label = $(this).find(".label").html();
		  literalLang=$(this).find(".literalLang").val();
		  literalType = $(this).find(".literalType").val();
		}
		var object = {"etype":etype,"eid":eid,"label":label};
		if(etype=="l"){
			object["literalLang"] = literalLang;
			object["literalType"] = literalType;
		}
		varray.push(object);
	});
	//对现有的重新约束
	var etype = entityType;
	var eid = entityID ;
	var container = $("<div class='filter'></div>");
	container.attr("fid",newMID);
	container.appendTo(".collectionMembers");
	
	var curMems = getCurrentMembers();
	if(displayLang=="en")
		$(".memberList").html("Filtering...");
	else if(displayLang=="zh")
		$(".memberList").html("过滤中...");
	var div = $("<div class='loading2'></div>").appendTo($(".memberList"));
	getEqualValueFilterResult(container,displayLang,dmtype,dmid,inverse,etype,eid,varray);
	
	enableFilter(newMID,curMems);
}

function addValueClassFilter(filterID){
	//改变mid，删除结果
	$(".collectionMembers").find(".filter[fid="+filterID+"]").remove();
	var originFilter = $(".filterList").find(".filterItem[mid="+filterID+"]");
	var newMID = getMID();
	originFilter.attr("mid",newMID);
	var dmtype = originFilter.attr("dmtype");
	var dmid = originFilter.attr("dmid");
	var inverse = originFilter.attr("inverse");
	var carray = new Array();
	originFilter.find(".fvconst .pvalue>li").each(function(){
		var class_set = $(this).attr("class_set");
		carray.push(class_set);
	});
	//对现有的重新约束
	var etype = entityType;
	var eid = entityID ;
	var container = $("<div class='filter'></div>");
	container.attr("fid",newMID);
	container.appendTo(".collectionMembers");
	
	var curMems = getCurrentMembers();
	if(displayLang=="en")
		$(".memberList").html("Filtering...");
	else if(displayLang=="zh")
		$(".memberList").html("过滤中...");
	var div = $("<div class='loading2'></div>").appendTo($(".memberList"));
	getValueClassFilterResult(container,displayLang,dmtype,dmid,inverse,etype,eid,carray);
	
	enableFilter(newMID,curMems);	
}

function filterMembersByAdd(dmtype,dmid,inverse,filterID){
	//第一步：将原始集合具有当前datamember取值非空的成员计算出来
	var etype = entityType;
	var eid = entityID ;
	var container = $("<div class='filter'></div>");
	container.attr("fid",filterID);
	container.appendTo(".collectionMembers");
	
	var curMems = getCurrentMembers();
	if(displayLang=="en")
		$(".memberList").html("Filtering...");
	else if(displayLang=="zh")
		$(".memberList").html("过滤中...");
	var div = $("<div class='loading2'></div>").appendTo($(".memberList"));
	
	getSingleFilterResult(container,displayLang,dmtype,dmid,inverse,etype,eid);
	
	//第二步: 将当前datamember取值成员和其它filter后的成员求交集
	////取得原始集合满足增加的filter的成员
	enableFilter(filterID,curMems);
}

/**
 * 启用已有的filter
 */
function enableFilter(filterID,curMems){
	var filteredMemsBox = $(".collectionMembers").find(".filter[fid="+filterID+"]");
	filteredMemsBox.removeClass("disabled");
	var array = new Array();
	for(i=0;i<curMems.length;i++){
		var member = curMems[i];
		var etype = member.etype;
		var eid = member.eid;
		if(filteredMemsBox.find("input[etype="+etype+"][eid="+eid+"]").length>0){
			array.push(member);
		}
	}
	$(".memberList").html("");
	for(i=0;i<array.length;i++){
		var ele = array[i];
		var etype = ele.etype;
		var eid = ele.eid;
		var element =$(".collectionMembers>div.origin").find("li[etype="+etype+"][eid="+eid+"]");
		if(element.length>0){
			$(".memberList").append(element.clone());
		}
	}
	//更改metadata
    $(".entity-memnum  .isFilter").show();
    $(".entity-memnum  .current").html(array.length);
    //清空array
    array = null;
    //通知视图区域要更新
    sendRefreshMsg();
}

/**禁用已有的filter
 */
function disableFilter(filterID){
	var array = new Array();
	var start = true;
	var hasFilter = false;
	$(".collectionMembers").find(".filter[fid="+filterID+"]").addClass("disabled");
	$(".collectionMembers").find(".filter").each(function(){
		if($(this).hasClass("disabled")){
			return;
		}
		var fid = $(this).attr("fid");
		if(!hasFilter){
			hasFilter = true;
		}
		if(start){
			start = false;
			$(this).find("input").each(function(){
				var etype = $(this).attr("etype");
				var eid = $(this).attr("eid");
				var obj = {"etype":etype,"eid":eid};
				array.push(obj);
			});
		}else{
			var newArray = new Array();
			for(i=0;i<array.length;i++){
				var element = array[i];
				var etype = element.etype;
				var eid=  element.eid;
				if($(this).find("input[etype="+etype+"][eid="+eid+"]").length>0){
					var obj = {"etype":etype,"eid":eid};
					newArray.push(obj);
				}
			}
			array = null;
			array = newArray;
		}
	});
	if(!hasFilter){
		$(".collectionMembers>div.origin>ul").children("li").each(function(){
			var etype= $(this).attr('etype');
			var eid = $(this).attr('eid');
			var obj = {"etype":etype,"eid":eid};
			array.push(obj);
		});
	}
	$(".memberList").html("");
	for(i=0;i<array.length;i++){
		var ele = array[i];
		var etype = ele.etype;
		var eid = ele.eid;
		var element =$(".collectionMembers>div.origin").find("li[etype="+etype+"][eid="+eid+"]");
		if(element.length>0){
			$(".memberList").append(element.clone());
		}
	}
	//更改metadata
    $(".entity-memnum  .isFilter").show();
    $(".entity-memnum  .current").html(array.length);
    //清空array
    array = null;
    //通知视图区域要更新
    sendRefreshMsg();
}

/**
 * 通知视图端需要进行刷新
 */
function sendRefreshMsg(){
	$(".subtab li.tableview").attr("refresh",1);
	$(".subtab li.listview").attr("refresh",1);
}


function getSingleFilterResult(container,displayLang,dmtype,dmid,inverse,etype,eid){
	var data = {};
	data["dmtype"] = dmtype;
	data["dmid"] = dmid;
	data["inverse"] = inverse;
	data["lang"] = displayLang;
	// which genre the eid belongs to
	data["etype"] = etype;
	data["eid"] = eid;
	data = JSON.stringify(data);
	data = ("foriginSet=" + encodeURIComponent(data));
	$.ajax({
		url:collection_servlet,
		async : false,
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
			for(i=0;i<result.length;i++){
				var item = result[i];
				var etype = item.etype;
				var eid = item.eid;
				var input = $("<input type='hidden' />");
				input.attr("etype",etype);
				input.attr("eid",eid);
				container.append(input);
			}
		}
	});
}

function getEqualValueFilterResult(container,displayLang,dmtype,dmid,inverse,etype,eid,varray){
	dmtype = parseInt(dmtype);
	dmid = parseInt(dmid);
	inverse =parseInt(inverse);
	var data = {};
	data["dmtype"] = dmtype;
	data["dmid"] = dmid;
	data["inverse"] = inverse;
	data["lang"] = displayLang;
	// which genre the eid belongs to
	data["etype"] = etype;
	data["eid"] = eid;
	data["varray"] =varray;
	data = JSON.stringify(data);
	data = ("foriginSetByEqualValue=" + encodeURIComponent(data));
	$.ajax({
		url:collection_servlet,
		async : false,
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
			for(i=0;i<result.length;i++){
				var item = result[i];
				var etype = item.etype;
				var eid = item.eid;
				var input = $("<input type='hidden' />");
				input.attr("etype",etype);
				input.attr("eid",eid);
				container.append(input);
			}
		}
	});	
}

function getMemberClassFilterResult(container,displayLang,dmtype,dmid,inverse,etype,eid,carray){
	dmtype = parseInt(dmtype);
	dmid = parseInt(dmid);
	inverse =parseInt(inverse);
	var data = {};
	data["dmtype"] = dmtype;
	data["dmid"] = dmid;
	data["inverse"] = inverse;
	data["lang"] = displayLang;
	// which genre the eid belongs to
	data["etype"] = etype;
	data["eid"] = eid;
	data["carray"] =carray;
	data = JSON.stringify(data);
	data = ("foriginSetByMemberClass=" + encodeURIComponent(data));
	$.ajax({
		url:collection_servlet,
		async : false,
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
			for(i=0;i<result.length;i++){
				var item = result[i];
				var etype = item.etype;
				var eid = item.eid;
				var input = $("<input type='hidden' />");
				input.attr("etype",etype);
				input.attr("eid",eid);
				container.append(input);
			}
		}
	});
}

function getValueClassFilterResult(container,displayLang,dmtype,dmid,inverse,etype,eid,carray){
	dmtype = parseInt(dmtype);
	dmid = parseInt(dmid);
	inverse =parseInt(inverse);
	var data = {};
	data["dmtype"] = dmtype;
	data["dmid"] = dmid;
	data["inverse"] = inverse;
	data["lang"] = displayLang;
	// which genre the eid belongs to
	data["etype"] = etype;
	data["eid"] = eid;
	data["carray"] =carray;
	data = JSON.stringify(data);
	data = ("foriginSetByValueClass=" + encodeURIComponent(data));
	$.ajax({
		url:collection_servlet,
		async : false,
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
			for(i=0;i<result.length;i++){
				var item = result[i];
				var etype = item.etype;
				var eid = item.eid;
				var input = $("<input type='hidden' />");
				input.attr("etype",etype);
				input.attr("eid",eid);
				container.append(input);
			}
		}
	});
}

function addTableViewDatamember(container,dmtype,dmid,inverse,name){
	var maxcolnum = parseInt($(container).attr("maxcolnum"));
	$(container).attr("maxcolnum",maxcolnum+1);
	//=====add header
	  var th = $("<th width='90' class='qitem'></th>");
	  th.attr("colid",maxcolnum+1);
	  th.attr("rowid",0);
	  th.attr("dmid",dmid);
	  th.attr("dmtype",dmtype);
	  th.attr("inverse",inverse);
	  th.attr("enum",count);
//	  var div =$("<div></div>");
//	  th.append(div);
	  var spanTitle = $("<span class='title'></span>");
	  spanTitle.text(name);
	  th.append(spanTitle);
	  $(spanTitle).addClass("green-yellow");
	  $(container).flexAppendHeader(th,maxcolnum+1);
//	  $(container).flexigrid();
	  
	  var num = $(container).find("tr").length;
	  var count = ((1+num)*num/2);
	  th.attr("enum",count);
	//=====for values
	//tbody
	$(container).find("tr").each(function(){
		var r = $(this).attr("rowid");
		if(r>0){
			var eid = parseInt($(this).attr("treid"));
			var etype = URI_ENTITY_STR;
			var members = new Array();
			members.push({"eid":eid+"","etype":etype+""});
			var vtd = $("<td></td>");
			vtd.attr("rowid",r);
			vtd.attr("colid",maxcolnum+1);
			$(this).append(vtd);
			var vdiv = $("<div class='tdDiv' style='width: 90px;'></div>");// style='width: 80px;'
			$(vtd).append(vdiv);
			var row = r;
			var col = maxcolnum+1;
			var grid = vdiv;//vtd;//container.find("[rowid="+row+"]").children("[colid="+col+"]");
			var ul = $("<ul></ul>");
			grid.html(ul);
			var status = "undownloaded" ;
			fetchValuesInCollectionBrowsing("table",displayLang, ul, dmtype, dmid, inverse, members, status,true);
		}
	});
//	$(container).flexRefresh(maxcolnum+1);
	  setHeaderState($("#dmTable"),$(th).find("span"));
}
function addListViewDatamember(ul,dmtype,dmid,inverse,name){
	var dmids = new Array();
	var dmtypes = new Array();
	var inverses = new Array();
	dmids.push(dmid);
	dmtypes.push(dmtype);
	inverses.push(inverse);
	var existContainer = ul.find("li[dmid=" + dmid + "][dmtype=" + dmtype + "][inverse="
			+ inverse + "]");
	if(existContainer.length>0){
		existContainer.prependTo(ul);
		return;
	}
	var li = $('<li class="prop"></li>');
	ul.prepend(li);
	li.attr("dmid", dmid);
	li.attr("dmtype", dmtype);
	li.attr("inverse", inverse);

	var titlebar = $("<div class='titlebar'></div>");
	li.append(titlebar);
	var spanLoading = $("<span class='loading'></span>");
	titlebar.append(spanLoading);
	var spanTitle = $("<span class='title'></span>");
	spanTitle.text(name);
	var status = $('<a class="status"></a>');
	titlebar.append(status);
	titlebar.append(spanTitle);

	var closeSpan = $("<a class='close'></a>");
	  if(displayLang=="en"){
		  closeSpan.attr("title","Remove");
	  }else if(displayLang=="zh"){
		  closeSpan.attr("title","移除") ; 
	  }
	  titlebar.append(closeSpan);
	var content = $("<div class='content'></div>");
	var pvalue = $("<ul class='pvalue'></ul>");
	pvalue.attr("dmtype", dmtype);
	pvalue.attr("dmid", dmid);
	li.append(content);
	content.append(pvalue);

	/* must be out of the above loop */
	for (i = 0; i < dmids.length; i++) {
		var dmid = dmids[i];
		var dmtype = dmtypes[i];
		var inverse = inverses[i];
		var container = ul.find(
				"li[dmid=" + dmid + "][dmtype=" + dmtype + "][inverse="
						+ inverse + "]").find(".pvalue");
		var genre = $(".entity-label").attr("genre");
		var eid = parseInt($(".entity-label").attr("eid"));
		var status = "undownloaded";
		var members = getCurrentMembers();
		updateValuesInCollectionBrowsing("list",displayLang,container,dmtype,dmid,inverse,members,status);
	}
}

function getTableViewDatamember(container,cmd){//cmd="init" or cmd ="update"
	 var data={};
	 var eid = parseInt(entityID);
	 data["collectionID"] = eid;
	 data["lang"] = displayLang;
	 var minTypeArray = getMinType();
	 var isInner = minTypeArray[0] ;
	 var classID = minTypeArray[1] ;
	 data["classID"] = classID;
	 data["isInner"]=isInner;
   data =  JSON.stringify(data);
   data =("initViewDMTable="+encodeURIComponent(data));
   $.ajax({
	  url:collection_servlet,
	  async:true,
	  data:data,
	  dataType:"json",
	  type:"post",
	  beforeSend:function(){
		  $(container).addClass("loading2");
	  },
   success:function(res){
 	  $(container).css("font-weight","400");
 	 // $(container).css("font-size","11px");
 	  var thead = container.find("thead");
 	  
 	  var htr = $("<tr></tr>");
 	  $(htr).attr("rowid",0);
 	  thead.append(htr);
//    var column = res["column"];    	  
 	  var qItems = res["list"];
 	  var dmids = new Array();
 	  var dmtypes =new Array();
 	  var inverses = new Array();
 	  //====for first th
 	  var th = $("<th width='90' align='center'></th>");
 	  th.attr("colid",0);
 	  th.attr("rowid",0);
     htr.append(th);
	  var spanTitle = $("<span class='title'></span>");
	  th.append(spanTitle);
	  
	  var emembers = getCurrentMembersWithName();//res["elist"];
	  var count = ((1+emembers.length)*emembers.length/2);
//	  alert(emembers.length+"|"+((1+emembers.length)*emembers.length/2));
 	  //=====for query items
 	  for(j=0;j<qItems.length;j++){
 		  //thead
 		  var item=qItems[j];
 		  var dmtype = parseInt(item["dmtype"]);
 		  var dmid = parseInt(item["dmid"]);
 		  dmids.push(dmid);
 		  dmtypes.push(dmtype);
 		  var name = item["name"];
 		  var inverse  = parseInt(item["inverse"]) ;
 		  inverses.push(inverse);
 		  var th = $("<th width='90' class='qitem'></th>");
 		  htr.append(th);
 		  th.attr("colid",j+1);
 		  th.attr("rowid",0);
 		  th.attr("dmid",dmid);
 		  th.attr("dmtype",dmtype);
 		  th.attr("inverse",inverse);
 		  th.attr("enum",count);
 		  var spanTitle = $("<span class='title green-gray'></span>");
 		  spanTitle.text(name);
 		  th.append(spanTitle);
 		}
 	  
	  	container.flexigrid({
	  		height: 'auto',
	  		minWidth: 30,
	  		alwaysLeft: true,//add by lqx for nDiv be left
	  		onColumnExplore: exploreEntityTableColulmnValue,
	  		onColumnRefresh: refreshColumnValue,
	  		onColumnRemove: removeColumn,
	  		checkColumnCanExplore: isColumnCanExplore/*,
	  		checkColumnCanRefresh:isColumnCanRefresh,
	  		checkColumnCanDelete: isColumnCanDelete*/
	  	});
	  	  $(container).attr("maxcolnum",qItems.length);
		//====for entities
//		  var emembers = res["elist"];
	  	  var tbody = $(container).find("tbody");
	  for(var i=0; i<emembers.length; i++){
		  var e = emembers[i];
		  var eid = e["eid"];
//		  var euri = e["euri"];
		  var ename = e["ename"];
		  var tr = $("<tr></tr>");
		  tr.attr("treid",eid);
		  tr.attr("trename",ename);
		  tr.attr("rowid",i+1);
		  $(tbody).append(tr);
		  var etd = $("<td class='sorted' style='vertical-align:center;'></td>");
		  etd.attr("colid",0);
		  etd.attr("rowid",i+1);
		  etd.attr("eid",eid);
		  $(tr).append(etd);
		  
		  var div = $("<div class='tdDiv' style='width: 90px; text-align:center;'></div>");// style='width: 80px;'
		  $(etd).append(div);
		  var ea = $("<a></a>");
		  var href = "/sview/entity/o"+eid;
		  $(ea).attr("href",href);
		  $(ea).attr("title",ename);
		  $(ea).text(ename);
//		  $(etd).append(ea);
		  $(div).append(ea);
	  }

		$("#dmTable").flexRefresh();
	  //====for values
   	for(var j=0;j<qItems.length;j++){
   		var header = $("th[colid="+(j+1)+"]").find("span.title");
   		$(header).removeClass("green-gray");
   		$(header).addClass("green-yellow");
   		//tbody
   		  for(var i=0; i<emembers.length; i++){
   	  		  var vtd = $("<td></td>");
   			  vtd.attr("colid",j+1);
   			  vtd.attr("rowid",i+1);
   			  var tr = $("tr[rowid="+(i+1)+"]");
   			  $(tr).append(vtd);
   			  var vdiv = $("<div class='tdDiv' style='width: 90px;'></div>");// style='width: 80px;'
   			  $(vtd).append(vdiv);
   			  var dmid = dmids[j];
 	  		  	var dmtype = dmtypes[j];
 	  		  	var inverse = inverses[j];
//   		  for(var i=0;i<emembers.length; i++){
   			  var eid = parseInt(emembers[i]["eid"]);
   			  var genre = URI_ENTITY_STR;
   			  var etype = URI_ENTITY_STR;
   			  var row = i+1;
   			  var col = j+1;
   			  var grid = vdiv;//vtd;//container.find("[rowid="+row+"]").children("[colid="+col+"]");
   				  var ul = $("<ul></ul>");
   				  grid.html(ul);
   			  var status = "undownloaded" ;
   			  if(cmd=="update"){
   				  var members = new Array();
   				  members.push({"eid":eid+"","etype":etype+""});
   				  updateValuesInCollectionBrowsing("table",displayLang, ul, dmtype, dmid, inverse, members, status,true);
   	   		  }else{
   	   		      var members = new Array();
				  members.push({"eid":eid+"","etype":etype+""});
   	   			  fetchValuesInCollectionBrowsing("table",displayLang, ul, dmtype, dmid, inverse, members, status,true);
   	   		  }
//   			  fetchValuesInCollectionBrowsing("table",displayLang, ul, dmtype, dmid, inverse, genre, eid, status,true);
//   			updateValuesInCollectionBrowsing("table",displayLang, ul, dmtype, dmid, inverse, genre, eid, status,true);
   		  }
   		  setHeaderState($("#dmTable"),header);
   	}
//   	container.flexReload();
	  	$(container).removeClass("loading2");
   }
 });
}

function setHeaderState(container,span){
	var th = $(span).parent().parent();
	var cid = $(th).attr("colid");
	var count = $(th).attr("enum");
	if(count==0){
		$(span).addClass("green-green");
	}else{
		setTimeout(function(){
			setHeaderState(container,span);
		}, 1000);
	}
	$(container).flexRefresh(cid);
}

function getTableViewDatamember_old(container){
	 var data={};
	 var eid = parseInt(entityID);
	 data["collectionID"] = eid;
	 data["lang"] = displayLang;
	 var minTypeArray = getMinType();
	 var isInner = minTypeArray[0] ;
	 var classID = minTypeArray[1] ;
	 data["classID"] = classID;
	 data["isInner"]=isInner;
   data =  JSON.stringify(data);
   data =("initViewDMTable="+encodeURIComponent(data));
   $.ajax({
	  url:collection_servlet,
	  async:true,
	  data:data,
	  dataType:"json",
	  type:"post",
	  beforeSend:function(){
		  $(container).addClass("loading2");
	  },
   success:function(res){
 	  $(container).css("font-weight","400");
 	  $(container).css("font-size","11px");
 	  var thead = container.find("thead");
 	  var tr = $("<tr></tr>");
 	  $(tr).attr("rowid",0);
 	  thead.append(tr);
//    var column = res["column"];    	  
 	  var qItems = res["list"];
 	  var dmids = new Array();
 	  var dmtypes =new Array();
 	  var inverses = new Array();
 	  
 	  var th = $("<th width='80'></th>");
 	  th.attr("colid",0);
 	  th.attr("rowid",0);
    tr.append(th);
    
	  var spanTitle = $("<span class='title'></span>");
	  th.append(spanTitle);
//	  container.flexigrid();


 	  for(i=0;i<qItems.length;i++){
 		  var item=qItems[i];
 		  var dmtype = item["dmtype"];
 		  var dmid = item["dmid"];
 		  dmids.push(dmid);
 		  dmtypes.push(dmtype);
 		  var name = item["name"];
 		  var inverse  = item["inverse"] ;
 		  inverses.push(inverse);
 		  var th = $("<th width='80' class='qitem'></th>");
 		  tr.append(th);
 		  th.attr("colid",i+1);
 		  th.attr("rowid",0);
 		  th.attr("dmid",dmid);
 		  th.attr("dmtype",dmtype);
 		  th.attr("inverse",inverse);
 		  
// 		  var titlebar = $("<div class='titlebar'></div>");
// 		  th.append(titlebar);
// 		  var spanLoading = $("<span class='loading'></span>");
// 		  titlebar.append(spanLoading);
 		  var spanTitle = $("<span class='title red'></span>");
 		  spanTitle.text(name);
 		  th.append(spanTitle);
 		  
// 		  var statusPoint = $("<span class='statuspoint'></span>");
// 		spanTitle.append(statusPoint);
//// 		  $(statusPoint).show();
// 		  var dataStatus = $("<span class='datastatus red'></span>");
// 		statusPoint.html(dataStatus);
//// 		  $(dataStatus).show();
// 		  var queryStatus = $("<span class='querystatus red'></span>");
// 		statusPoint.append(queryStatus);
 		
// 		  $(queryStatus).show();
// 		  var status = $('<a class="status"></a>');
// 		  titlebar.append(status);
// 		  titlebar.append(spanTitle);
// 		  var explorerSpan = $("<span class='explore'></span>");
// 		  if(displayLang=="en"){
// 			explorerSpan.attr("title","Explore this collection");
// 		  }else if(displayLang=="zh"){
// 			explorerSpan.attr("title","浏览取值集合") ; 
// 		  }
// 		  titlebar.append(explorerSpan);
// 		  var content = $("<div class='content'></div>");
// 		  var pvalue = $("<ul class='pvalue'></ul>");
// 		  pvalue.attr("dmtype",dmtype);
// 		  pvalue.attr("dmid",dmid);
// 		  th.append(content) ;
// 		  content.append(pvalue);
 	  }
	  	container.flexigrid({
	  		height: 'auto',
	  		minWidth: 30,
	  		onColumnExplore: exploreEntityTableColulmnValue,
	  		onColumnRefresh: refreshColumnValue,
	  		onColumnRemove: removeColumn,
	  		checkColumnCanExplore: isColumnCanExplore/*,
	  		checkColumnCanRefresh:isColumnCanRefresh,
	  		checkColumnCanDelete: isColumnCanDelete*/
	  	});
 	  var emembers = res["elist"];
 	  var tbody = $(container).find("tbody");
 	  for(var i=0; i<emembers.length; i++){
 		  var e = emembers[i];
 		  var eid = e["eid"];
 		  var euri = e["euri"];
 		  var ename = e["ename"];
 		  var tr = $("<tr></tr>");
 		  tr.attr("treid",eid);
 		  tr.attr("treuri",euri);
 		  tr.attr("rowid",i+1);
 		  $(tbody).append(tr);
 		  var etd = $("<td></td>");
 		  etd.attr("colid",0);
 		  etd.attr("rowid",i+1);
 		  etd.attr("eid",eid);
 		  etd.attr("euri",euri);
 		  $(tr).append(etd);
 		  
 		  var div = $("<div class='tdDiv' style='width: 90px;'></div>");// style='width: 80px;'
 		  $(etd).append(div);
 		  
 		  var ea = $("<a ></a>");
 		  var href = "/sview/entity/o"+eid;
 		  $(ea).attr("href",href);
 		  $(ea).attr("title", euri);
 		  $(ea).text(ename);
// 		  $(etd).append(ea);
 		  $(div).append(ea);
 		  for(var j=0; j<qItems.length; j++){
 			  var vtd = $("<td></td>");
 			  vtd.attr("colid",j+1);
 			  vtd.attr("rowid",i+1);
 			  $(tr).append(vtd);
// 			  vtd.html(i+","+j);
 			  var vdiv = $("<div class='tdDiv' style='width: 90px;'></div>");// style='width: 80px;'
 			  $(vtd).append(vdiv);
 			var dmid = dmids[j];
		  var dmtype = dmtypes[j];
		  var inverse = inverses[j];
//		  for(var i=0;i<emembers.length; i++){
			  var eid = parseInt(emembers[i]["eid"]);
			  var etype = URI_ENTITY_STR;
			  var members = new Array();
			  members.push({"eid":eid+"","etype":etype+""});
			  var row = i+1;
			  var col = j+1;
			  var grid = vdiv;//vtd;//container.find("[rowid="+row+"]").children("[colid="+col+"]");
//			  alert(row+"|"+col+"|"+grid.length);
   			  var ul = $("<ul></ul>");
   			  grid.html(ul);
			  var status = "undownloaded" ;
//			  fetchValuesInBrowsing(displayLang,grid,dmtype,dmid,inverse,genre,eid,status);
//			  fetchValues(displayLang, ul, dmtype, dmid, inverse, genre, eid, status);
			  fetchValuesInCollectionBrowsing("table",displayLang, ul, dmtype, dmid, inverse, members, status,true);
//		  }
 		  }
 	  }
   	container.flexReload();
////
//	  	container.flexigrid({
//	  		height: 'auto',
//	  		minWidth: 30,
//	  		onColumnExplore: exploreEntityTableColulmnValue,
//	  		onColumnRefresh: refreshColumnValue,
//	  		onColumnRemove: removeColumn,
//	  		checkColumnCanExplore: isColumnCanExplore/*,
//	  		checkColumnCanRefresh:isColumnCanRefresh,
//	  		checkColumnCanDelete: isColumnCanDelete*/
//	  	});
   	$(container).find(".tdDiv").find("ul").each(function(){
   		var num = $(this).attr("num");
   		if(num==0){
   			$(this).append("none");
   		}
   	});
   	
   	
	  	  $(container).removeClass("loading2");
// 	container.extend({
// 		height: 'auto',
// 		onColumnExplore: exploreEntityTableColulmnValue,
// 		onColumnRefresh: refreshColumnValue,
// 		onColumnRemove: removeColumn,
// 		checkColumnCanExplore: isColumnCanExplore/*,
// 		checkColumnCanRefresh:isColumnCanRefresh,
// 		checkColumnCanDelete: isColumnCanDelete*/
// 	});
 	
// 	$(container).find("div").each(function(){
// 		if($(this).hasClass("statuspoint") || $(this).hasClass("datastatus") || $(this).hasClass("querystatus")){
// 			$(this).removeClass("sundefined");
// 		}
// 	});
// 	container.find("[tid=3]").find("[tid=5]").text("a");//="a";
// 	  alert("cc"+container.find("[tid=3]").find("[tid=5]").text());
 	  
// 	for(var j=0;j<dmids.length;j++){
//		  var dmid = dmids[j];
//		  var dmtype = dmtypes[j];
//		  var inverse = inverses[j];
//		  for(var i=0;i<emembers.length; i++){
//			  var eid = parseInt(emembers[i]["eid"]);
//			  var genre = URI_ENTITY_STR;
//			  var row = i+1;
//			  var col = j+1;
//			  var grid = container.find("[rowid="+row+"]").children("[colid="+col+"]");
////			  alert(row+"|"+col+"|"+grid.length);
// 			  var ul = $("<ul></ul>");
// 			  grid.html(ul);
//			  var status = "undownloaded" ;
////			  fetchValuesInBrowsing(displayLang,grid,dmtype,dmid,inverse,genre,eid,status);
////			  fetchValues(displayLang, ul, dmtype, dmid, inverse, genre, eid, status);
//			  fetchValuesInCollectionBrowsing("table",displayLang, ul, dmtype, dmid, inverse, genre, eid, status,false);
//		  }
//	  }
 	  /*must be out of the above loop*/
// 	  for(i=0;i<dmids.length;i++){
// 		  var dmid = dmids[i];
// 		  var dmtype = dmtypes[i];
// 		  var inverse = inverses[i];
// 		  var container = box.find("li[dmid="+dmid+"][dmtype="+dmtype+"]").find(".pvalue");
// 		  var genre = $(".entity-label").attr("genre");
// 		  var eid = parseInt($(".entity-label").attr("eid"));
// 		  var status = "undownloaded" ;
// 		  fetchValuesInBrowsing(displayLang,container,dmtype,dmid,inverse,genre,eid,status);
// 	  }
 	  
//	  $.fn.flexReset = function(p){
//		  return this.each(function(){
//			  if(this.grid){
//				  $.extend(this.p,{
//					  width: 80
//					 resizable:true
//				  });
//				  this.grid.buildpager();
//				  
//			  }
//		  })
//	  }
   }
 });
}


function init(){
	//quick search widget
  	$.widget( "custom.mycomplete", $.ui.autocomplete, {
		_renderMenu: function( ul, items ) {
			var that = this;
			currentCategory = "";
			$.each( items, function( index, item ) {
				if ( item.category != currentCategory ) {
					ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
					currentCategory = item.category;
				}
				that._renderItemData( ul, item );
			});
		},
		_renderItemData:function( ul, item ) {
		    var dmtype = item.dmtype;
		    var dmid = item.dmid;
		    var inverse = item.inverse;
		    var name = item.name;
		    var vtype = item.vtype;
		    var arity = item.arity;
		    var funct = item.functional;
		    var hasAuthor =item.hasAuthor;
		
		    var li = showMycompleteItem(dmtype,dmid,arity,inverse,vtype,funct,name,hasAuthor);
			li.appendTo(ul);
			ul.find("li:last>div").addClass("final");
			return li;
		}
	});
	$(".qitem-box-inview .qitem" ).mycomplete({
		source: function( request, response ) {
			 var data={};
			 data["kw"] = request.term;
			 data["lang"] = displayLang;
			 data["etype"] = parseInt(entityType);
			 data["eid"] = parseInt(entityID);
			 var minTypeArray = getMinType();
			 var isInner = minTypeArray[0] ;
			 var classID = minTypeArray[1] ;
			 data["isInner"] = isInner;
			 data["cid"] = classID ;
			 data["user"] = getUser();
			 data["groupID"] = $("#groupID").val();
		     data =  JSON.stringify(data);
			 data=("dmsearch="+encodeURIComponent(data));
			$.ajax({
				url: VESERV,
				dataType: "json",
				data: data,
				type:"post" ,
				success: function( data ) {
					response(data);
				}
			});
		},
		minLength:0
	}).focus(function () {
		if ($(this).mycomplete("widget").is(":visible")) {
             return;
        }
		$(this).mycomplete("search", $(this).val());
    });
	
  	$.widget( "custom.mycompleteFilter", $.ui.autocomplete, {
		_renderMenu: function( ul, items ) {
			var that = this,
			currentCategory = "";
			$.each( items, function( index, item ) {
				if ( item.category != currentCategory ) {
					ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
					currentCategory = item.category;
				}
				that._renderItemData( ul, item );
			});
		},
		_renderItemData:function( ul, item ) {
		    var dmtype = item.dmtype;
		    var dmid = item.dmid;
		    var inverse = item.inverse;
		    var name = item.name;
		    var vtype = item.vtype;
		    var arity = item.arity;
		    var funct = item.functional;
		    var hasAuthor =item.hasAuthor;
		
		    var li = collectionFilter(dmtype,dmid,arity,inverse,vtype,funct,name,hasAuthor);
			li.appendTo(ul);
			ul.find("li:last>div").addClass("final");
			return li;
		}
	});
	$( ".qitem-box-inmem .qitem" ).mycompleteFilter({
		source: function( request, response ) {
			 var data={};
			 data["kw"] = request.term;
			 data["lang"] = displayLang;
			 data["etype"] = parseInt(entityType);
			 data["eid"] = parseInt(entityID);
			 var minTypeArray = getMinType();
			 var isInner = minTypeArray[0] ;
			 var classID = minTypeArray[1] ;
			 data["isInner"] = isInner;
			 data["cid"] = classID ;
			 data["user"] = getUser();
			 data["groupID"] = $("#groupID").val();
		     data =  JSON.stringify(data);
			 data=("dmsearch="+encodeURIComponent(data));
			$.ajax({
				url: VESERV,
				dataType: "json",
				data: data,
				type:"post" ,
				success: function( data ) {
					response(data);
				}
			});
		},
		minLength:0
	}).focus(function () {
		if ($(this).mycompleteFilter("widget").is(":visible")) {
            return;
       }
		$(this).mycompleteFilter("search", $(this).val());
   });
	
	//store origin members
	var originMembers = $(".collectionMembers>div.origin");
	var memList = $("<ul></ul>").appendTo(originMembers);
	memList.html($(".memberList").html());
	
	//get the pop views 
	var minTypeArray = getMinType();
	var isInner = minTypeArray[0] ;
	var minClassID = minTypeArray[1] ;
	var lang =getDisplayLang();
	$("li.listview a").tab("show");
	$("li.listview").addClass("inited");
	showView("list");
	
	$(".entity-type .type>span").each(function(){
		if($(this).text()==""){
			fetchLabel($(this),parseInt($(this).attr("type_id")),displayLang);
		}
	});
	
}

function initViewOnTabClick(obj){
	   $(obj).parent().addClass("inited");
	   var minTypeArray = getMinType();
	   var isInner = minTypeArray[0] ;
	   var minClassID = minTypeArray[1] ;
	   var user = getUser();
	   var start = 0;
	   var length =10;
	   var lang =getDisplayLang();
	   var curPage = 1;
	   var userLogin = 0;
	   if($(obj).parent().hasClass("tableview")){
		   //process the popular entities
		   showView("table");
	   }else if($(obj).parent().hasClass("listview")){
		   //process mine entities
		   showView("list");
	   }
}

function updateViewOnTabClick(obj){
	   $(obj).parent().attr("refresh",0);
	   if($(obj).parent().hasClass("tableview")){
		   //process the popular entities
		   updateView("table");
		  
	   }else if($(obj).parent().hasClass("listview")){
		   //process mine entities
		   updateView("list");
	   }
}

function nameCheck(e){
	var displayLang = $("#display-lang").val();
	var flag =true;
	blurState(e);
	var val =$(e).val();
	if(val==""){
		var msg =$(e).parent().find(".errorMsg");
		var textEn = "Please enter a name";
		var textZhSimple ="请输入名称";
		if(displayLang=="en")
			msg.text(textEn);
		else if(displayLang=="zh")
			msg.text(textZhSimple);
		msg.show();
		$(e).css("border-color","red");
		flag = false;
	}else if(val.indexOf("%")>=0){
		var msg =$(e).parent().find(".errorMsg");
		var textEn = "Illegal character '%'";
		var textZhSimple ="非法字符'%'";
		if(displayLang=="en")
			msg.text(textEn);
		else if(displayLang=="zh")
			msg.text(textZhSimple);
		msg.show();
		$(e).css("border-color","red");
		flag = false;
	}
	if(!flag)
		return false;
	return true;
}

function existBookmark(name,author,lang,etype,eid){
	 var flag = false;
	 var data={};
	 data["author"] = author;
	 data["name"] = name;
	 data["lang"] = lang;
	 data["etype"] = etype;
	 data["eid"] = eid;
	 data =  JSON.stringify(data);
	 data =("existBookmark="+encodeURIComponent(data));
	 $.ajax({
	   	  url:views_servlet,
	   	  async:false,
	   	  data:data,
	   	  dataType:"text",
	   	  type:"post",
	   	  success:function(result){
			if(result=="exist"){
				flag = true;	 
			}
		  }	   	  
     });
	 
	 return flag;
}

function saveBookmark(name,author,lang,etype,eid){
	 var data={};
	 data["author"] = author;
	 data["name"] = name;
	 data["lang"] = lang;
	 data["etype"] = etype;
	 data["eid"] = eid;
	 data =  JSON.stringify(data);
	 data =("storeBookmark="+encodeURIComponent(data));
	 $.ajax({
	   	  url:views_servlet,
	   	  async:true,
	   	  data:data,
	   	  dataType:"text",
	   	  type:"post"		 
     });
}


function showMycompleteItem(dmtype,dmid,arity,inverse,vtype,funct,name,hasAuthor){
	var li = $("<li class='mycomplete-item'></li>");
	var div = $('<div class="mycomplete-item-box"></div>');
	
	var a = $('<a class ="mycomplete-item-link" href="javascript:void(0)"></a>');
	div.append(a);
	//////////////
	a.attr("dmtype",dmtype) ;		
	a.attr("dmid",dmid) ;
	a.html(name);
	
	a.click(function(){
		var table = $("#dmTable");
		addTableViewDatamember(table,dmtype,dmid,inverse,name);
		var ul = $(".listViewContainer");
		addListViewDatamember(ul,dmtype,dmid,inverse,name);
	    $(".qitem-box-inview .qitem").val(name);
	    $(".qitem-box-inview .qitem").removeClass("focus");
	    $(".qitem-box-inview .qitem" ).mycomplete("close");
	});
	/////////////
	li.append(div);
	return li;
}

function collectionFilter(dmtype,dmid,arity,inverse,vtype,funct,name,hasAuthor){
	var li = $("<li class='mycomplete-item'></li>");
	var div = $('<div class="mycomplete-item-box"></div>');
	
	var a = $('<a class ="mycomplete-item-link" href="javascript:void(0)"></a>');
	div.append(a);
	//////////////
	a.attr("dmtype",dmtype) ;		
	a.attr("dmid",dmid) ;
	a.html(name);
	
	a.click(function(){
		var ul = $(".filterList");
		$(".qitem-box-inmem .qitem").removeClass("focus");
	    $(".qitem-box-inmem .qitem").val(name);
	    $(".qitem-box-inmem .qitem" ).mycompleteFilter("close");
		addFilter(ul,dmtype,dmid,inverse,name,vtype);
	});
	/////////////
	li.append(div);
	return li;
}

/*show view content related*/
function showView(viewType){
	var container ;
	if(viewType=="table")
		container = $("#tableView .vcontent");
	else{
		container = $("#listView .vcontent");
	}
	container.html("");
	var vsectSpan = $('<span class="vsetc"><button class="vset ui-button ui-widget ui-state-default ui-corner-all ui-button-icons-only"  > <span class="icon-gear"></span><span class="icon-triangle-1-s"></span></button></span>');
	var menuDiv= null;
	if(displayLang=='en')
		menuDiv =$('<div class="dmenu smenu" ><ol><li><a href="javascript:void(0)" class="view-ds">Show datasources</a></li></ol></div>');
	else if(displayLang=='zh')
		menuDiv =$('<div class="dmenu smenu" ><ol><li><a href="javascript:void(0)" class="view-ds">显示数据源</a></li></ol></div>');
	vsectSpan.append(menuDiv);
	if(viewType=="table"){
		//first show vname
		var relativeDiv= $("<div class='relative'></div>");
//		container.append(relativeDiv);
		container.html(relativeDiv);
		var setDiv = $("<div class='setDiv'></div>");
		setDiv.append(vsectSpan.clone());
		relativeDiv.append(setDiv);
		var tableDiv = $("<div id='dmTable'></div>");
		relativeDiv.append(tableDiv);
		var thead = $("<thead></thead>");
		tableDiv.html(thead);
		var tbody = $("<tbody></tbody>");
		tableDiv.append(tbody);
		getTableViewDatamember(tableDiv);
//		relativeDiv.attr("vvid",vid);
//		var vnameSpan = $("<span class='vname'></span>").text(vname);
//		relativeDiv.append(vnameSpan);
//		relativeDiv.append(vsectSpan.clone());
//		container.append(relativeDiv);
//		var table = $("<table class='tableView'></table>");
//		var thead=$("<thead></thead>");
//		var tbody = $("<tbody></tbody>");
//		table.append(thead);
//		table.append(tbody);
//		container.append(table);
//		//get the property list skeleton
//		//ajax to get the property list and show the computing status
//		var etype = parseInt(entityType);
//		var eid = parseInt(entityID);
//		getTableViewDatamember(vid,table,etype,eid);
	}else{
		var relativeDiv= $("<div class='relative'></div>");
		var setDiv = $("<div class='setDiv'></div>");
		setDiv.append(vsectSpan.clone());
		relativeDiv.append(setDiv);
		container.append(relativeDiv);
		var ul = $("<ul class='listViewContainer'></ul>");
		relativeDiv.append(ul);
		ul.sortable({
			  accept:'.listViewContainer>.prop',
			  tolerance:'pointer',
			  helper:"clone"
	    });

		getListViewDatamember(ul);
	}
}

function updateView(viewType){
	if(viewType=="table"){
		container = $("#tableView .vcontent");
		updateTableViewDatamemberValues(container);
	}else{
		container = $("#listView .vcontent");
		var ul = container.find(".listViewContainer");
		updateListViewDatamemberValues(ul);
	}
}

function fetchValuesInCollectionBrowsing(op,displayLang,container,dmtype,dmid,inverse,members,status,flag){
	var data = {};
	data["dmtype"] = dmtype;
	data["dmid"] = dmid;
	data["inverse"] = inverse;
	data["lang"] = displayLang;
	// which genre the eid belongs to
	data["members"] = members;
	data["status"] = status;
	data = JSON.stringify(data);
	data = ("cviewDMValue=" + encodeURIComponent(data));
	var async = true;
	if (flag != "undefined") {
		async = flag;
	}
	$.ajax({
		url:collection_servlet,
		async : async,
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
			handleValuesInCollectionBrowsing(op,result,container,displayLang);
			var status = result["status"];
			if (status != "stop") {
				setTimeout(function() {
					fetchValuesInCollectionBrowsing(op,displayLang,container, dmtype, dmid, inverse,
									members, status, flag);
					}, 1000);
			} else {
				    var titlebar = $(container).parent().parent().find(".titlebar");
				    titlebar.find(".loading").hide();	
				
					$(container).children("li:last").addClass("final");
					if(op=="table"){
						//remove old datasources
						var context = $("#tableView .vcontent").children(".relative");
						context.find(".dsBox").remove();
						
						var rowid = $(container).parent().parent().attr("rowid");
						var colid = $(container).parent().parent().attr("colid");
						var header = $("[colid="+colid+"][rowid=0]");
						$(header).attr("enum",($(header).attr("enum")-rowid));
						
						//store related datasources
						var dsbox = $("<div class='hidden datasource'></div>").appendTo(container);
						var srcDocs = result["srcDocs"];
						for(j=0;j<srcDocs.length;j++){
							var docobj = srcDocs[j];
							var id = docobj.id;
							var uri = docobj.uri;
							var dsdiv = $("<div class='ds'><a></a></div>").appendTo(dsbox);
							dsdiv.find("a").attr("href",uri);
							dsdiv.find("a").attr("title",uri);
							dsdiv.find("a").attr("dsid",id);
							dsdiv.find("a").html(uri);
						}
					}else if(op=="list"){
						//check whether browsing collection available
						if(container.children("li[etype=o]").length>0){
							var explorerSpan = $("<span class='explore'></span>");
				   			if(displayLang=="en"){
				   				explorerSpan.attr("title","Explore this collection");
				   			}else if(displayLang=="zh"){
				   				explorerSpan.attr("title","浏览取值集合") ; 
				   			}
				   			titlebar.append(explorerSpan);
						}
						
						var dsbox = $("<div class='hidden datasource'></div>").appendTo(container);
						var srcDocs = result["srcDocs"];
						//store related datasources
						for(j=0;j<srcDocs.length;j++){
							var docobj = srcDocs[j];
							var id = docobj.id;
							var uri = docobj.uri;
							var dsdiv = $("<div class='ds'><a></a></div>").appendTo(dsbox);
							dsdiv.find("a").attr("href",uri);
							dsdiv.find("a").attr("title",uri);
							dsdiv.find("a").attr("dsid",id);
							dsdiv.find("a").html(uri);
						}
					}
			}
		}
	});
}

function updateValuesInCollectionBrowsing(op,displayLang,container,dmtype,dmid,inverse,members,status,flag){
	var meid = eid;
	var data = {};
	dmtype = parseInt(dmtype);
	dmid = parseInt(dmid);
	inverse = parseInt(inverse);
	data["dmtype"] = dmtype;
	data["dmid"] = dmid;
	data["inverse"] = inverse;
	data["lang"] = displayLang;
	//current members of this collection
	data["members"] = members;
	data["status"] = status;
	data = JSON.stringify(data);
	data = ("cviewDMValue=" + encodeURIComponent(data));
	var async = true;
	if (flag != "undefined") {
		async = flag;
	}
	$.ajax({
		url:collection_servlet,
		async : async,
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
			handleValuesInCollectionBrowsing(op,result,container,displayLang);

			var status = result["status"];
			if (status != "stop") {
				setTimeout(function() {
					updateValuesInCollectionBrowsing(op,displayLang,container, dmtype, dmid, inverse,
									members, status, flag);
						}, 300);
			} else {
				var titlebar = $(container).parent().parent().find(".titlebar");
			    titlebar.find(".loading").hide();
			    
				$(container).children("li:last").addClass("final");
				if(op=="table"){
					var rowid = $(container).parent().parent().attr("rowid");
					var colid = $(container).parent().parent().attr("colid");
					var header = $("[colid="+colid+"][rowid=0]");
					$(header).attr("enum",($(header).attr("enum")-rowid));
					
					//store related datasources
					var dsbox = $("<div class='hidden datasource'></div>").appendTo(container);
					var srcDocs = result["srcDocs"];
					for(j=0;j<srcDocs.length;j++){
						var docobj = srcDocs[j];
						var id = docobj.id;
						var uri = docobj.uri;
						var dsdiv = $("<div class='ds'><a></a></div>").appendTo(dsbox);
						dsdiv.find("a").attr("href",uri);
						dsdiv.find("a").attr("title",uri);
						dsdiv.find("a").attr("dsid",id);
						dsdiv.find("a").html(uri);
					}
				}else if(op=="list"){
					//check whether browsing collection available
					if(container.children("li[etype=o]").length>0){
						var explorerSpan = $("<span class='explore'></span>");
			   			if(displayLang=="en"){
			   				explorerSpan.attr("title","Explore this collection");
			   			}else if(displayLang=="zh"){
			   				explorerSpan.attr("title","浏览取值集合") ; 
			   			}
			   			titlebar.append(explorerSpan);
					}
					
					//remove old datasources
					var context = $("#listView .vcontent").children(".relative");
					context.find(".dsBox").remove();
					
					var dsbox = $("<div class='hidden datasource'></div>").appendTo(container);
					var srcDocs = result["srcDocs"];
					//store related datasources
					for(j=0;j<srcDocs.length;j++){
						var docobj = srcDocs[j];
						var id = docobj.id;
						var uri = docobj.uri;
						var dsdiv = $("<div class='ds'><a></a></div>").appendTo(dsbox);
						dsdiv.find("a").attr("href",uri);
						dsdiv.find("a").attr("title",uri);
						dsdiv.find("a").attr("dsid",id);
						dsdiv.find("a").html(uri);
					}
				}
			}
		}
	});	
}

function handleValuesInCollectionBrowsing(op,result,container,displayLang){
	var values = result["values"];
	var hideLi = false;
	if(op=="table" && values.length>1){
		hideLi = true;
		$(container).attr("num",values.length);
		if(values.length==0){
			container.append("none");
		}
	}
	$(container).html("");
	for (i = 0; i < values.length; i++) {
		var item = values[i];
		var etype = item["etype"];
		var eid = item["eid"];
		var euri = item["euri"];
		
		var li = $("<li></li>");
		$(container).append(li);
		if(op=="table"){
			$(li).addClass("value");
		}
		li.attr("etype", etype);
		li.attr("eid", eid);
		var valueLabel = item["valueLabel"];
		if (etype == "l") {
			li.html(valueLabel);
		} else {
			if(item.directuri==1){
				var alink = $("<a class='vlink' target='_blank'></a>");
				alink.addClass("directlink");
				alink.text(euri);
				alink.attr("href", euri);
				alink.attr("title", euri);
				li.append(alink);
			}else if(item.directlabel==1){
				li.text(valueLabel);
			}else if(item.isimage==1){
				var img = $("<img/>");
				img.attr("src",euri);
				if(displayLang=="en"){
					img.attr("Loading Image");
				}else if(displayLang=="zh"){
					img.attr("加载图片");
				}
				li.append(img);
			}
			else{
				var alink = $("<a class='vlink' target='_blank'></a>");
				alink.text(valueLabel);
				alink.attr("href", getEntityLinkHref(etype, eid,displayLang));
				alink.attr("title", euri);
				li.append(alink);
				//对于uri，异步取label
				var needLabel = item["needLabel"];
				if(needLabel){
					fetchLabel(alink,eid,displayLang);
				}
			}
		}
		//for tableView hideLi
		if(hideLi){
			if(i>0){
				$(li).hide();
			}
//			if (i==0){
//				var a=$("<div class='moreV'></div>");
//				var text = "show all ("+values.length+")";
//				if(displayLang=="zh"){
//					text = "显示全部 ("+values.length+")";
//				}
//				$(a).text(text);
//				$(a).click(function(){
//					$(this).parent().siblings().show();
//					$(this).hide();
//				});
//				$(li).append(a);
//			}
		}
		//end of  tableView hideLi
		if(op=="list"){
			var memberArray = item["memberArray"];
			var memNumSpan = $("<a class='cmem_num_box'>(<span class='cmem_num'></span>)</a>");
			memNumSpan.find(".cmem_num").html(memberArray.length);
			li.append(memNumSpan);
			if(displayLang=="en"){
				memNumSpan.attr("title","See members have this value");
			}else if(displayLang=="zh"){
				memNumSpan.attr("title","查看具有该取值的成员");
			}
			var memDiv = $("<div class='hidden memDiv'><ul class='memList'></ul></div>");
			li.append(memDiv);
			for(j=0;j<memberArray.length;j++){
				var member = memberArray[j];
				var memType = member["memberType"];
				var memID = member["memberID"];
				var memLabel = member["memberLabel"];
				var memItem = $("<li></li>");
				memItem.attr("memtype",memType);
				memItem.attr("memid",memID);
				memDiv.find("ul").append(memItem);
				var link = $("<a target='_blank'></a>").html(memLabel);
				memItem.append(link);
				var genre ;
				var href = "/sview/entity/"+memType+memID+"?lang="+displayLang;
				link.attr("href",href);
			}
		}
	}
	//for tableView hideLi
	if(hideLi){
		//add moreV
		var moreLi = $("<li class='moreV'></li>");
			var ma=$("<div></div>");
			var text = "show all ("+values.length+")";
			if(displayLang=="zh"){
				text = "显示全部 ("+values.length+")";
			}
			$(ma).text(text);
			$(moreLi).click(function(){
				$(this).siblings().show();
				$(this).siblings(".lessV").show();
				$(this).hide();
			});
			$(moreLi).append(ma);
			$(container).append(moreLi);
		//add lessV
		var lessLi = $("<li class='lessV'></li>");
		var la = $("<div></div>");
		var text = "<<hide";
		if(displayLang=="zh"){
			text = "<<隐藏";
		}
		$(la).text(text);
		$(lessLi).click(function(){
			$(this).siblings("li:first").nextAll().hide();
			$(this).siblings(".moreV").show();
			$(this).hide();
		});
		$(lessLi).append(la);
		$(lessLi).hide();
		$(container).append(lessLi);
	}
	if(values.length==0){
		var text = "none";
		if(displayLang=="zh"){
			text = "空";
		}
		var li = $("<li class='placeHolder'></li>");
		$(container).append(li);
		var span = $("<span></span>");
		$(span).text(text);
		$(span).attr("title","no value");
		$(li).append(span);
	}
	
}


function isColumnCanExplore(th){
	var colid = th.attr("colid");
	var collection = new Array();
	var flag = false;
	$("[colid="+colid+"][rowid!=0]").each(function(){
		var lis = $(this).find("ul").find("li")
		if(lis.length>0){
			$(lis).each(function(){
				var etype = $(this).attr("etype");
				var eid = $(this).attr("eid");
				if(eid!=null && etype!=null){
					if(parseInt(eid)>0 && etype=="o"){
						flag = true;
						return flag;
					}
				}
			});
		}
	});
	return flag;
}

function exploreEntityTableColulmnValue(th,b){
	var colid = th.attr("colid");
	var collection = new Array();
	$("[colid="+colid+"][rowid!=0]").each(function(){
		var lis = $(this).find("ul").find("li")
		if(lis.length>0){
			$(lis).each(function(){
				var etype = $(this).attr("etype");
				var eid = $(this).attr("eid");
				if(eid!=null && etype!=null){
					var object = {"etype":etype,"eid":eid};
					collection.push(object);
				}
			});
		}
	});
	var entityLabel = $('.entity-label').html();
	var dmtitle= $(th).find(".title").html();
	var name = entityLabel+"."+dmtitle;
	browseCollection(collection,name);
}
function refreshColumnValue(th,b){
	//remove old datasources
	var context = $("#tableView .vcontent").children(".relative");
	context.find(".dsBox").remove();
	
//	alert("refresh:"+th+"|"+b);
	var colid = $(th).attr("colid");
	if(colid==0){//to be completed
		$("#dmTable").flexRefresh(colid);
		return;
	}
	$("#dmTable").flexRefresh(colid);
	$(th).find("span").removeClass("green-green");
	$(th).find("span").addClass("green-yellow");
	var num = $("#dmTable").find("tr").length;
	var count = ((1+num)*num/2);
	$(th).attr("enum",count);
	
	var dmtype = parseInt($(th).attr("dmtype"));
	var dmid = parseInt($(th).attr("dmid"));
	var inverse = parseInt($(th).attr("inverse"));
	$("#dmTable").find("tr").each(function(){
		var r = $(this).attr("rowid");
		if(r>0){
			var eid = parseInt($(this).attr("treid"));
			var etype = URI_ENTITY_STR;
			var members = new Array();
		    members.push({"eid":eid+"","etype":etype+""});
			var vtd = $(this).find("td[rowid="+r+"][colid="+colid+"]");
			var ul = $(vtd).find("ul");
			$(ul).html("");
			var status = "undownloaded" ;
			fetchValuesInCollectionBrowsing("table",displayLang, ul, dmtype, dmid, inverse, members, status,true);
		}
	});
	setHeaderState($("#dmTable"),$(th).find("span"));
}
function removeColumn(th){
	var id = $(th).attr("axis").replace("col","");
	$("#dmTable").flexRemoveCol(id);
	
	//remove old datasources
	var context = $("#tableView .vcontent").children(".relative");
	context.find(".dsBox").remove();
	
//	var colid = th.attr("colid");
//	var collist = $("[colid="+colid+"]");
//	$(".nDiv").toggle();
//	$("#dmTable").flexReload();
//	$("#dmTable").flexHideCol(colid,true);
//	$("#dmTable").flexToggleCol(colid,true);
//	$("#dmTable").rePosDrag();
//	$("#dmTable").dragEnd;
	
//	alert("rem"+col.attr("colid"));
}

/*start: filter value constraint*/
function memberClassConstraint(container){
	container.addClass("inited");
	dmtype = parseInt(dmtype);
	dmid = parseInt(dmid);
	inverse = parseInt(inverse);
	var array = getCurrentMembers();
	var data = {};
	data["members"] = array;
	data["lang"] = displayLang;
	data = JSON.stringify(data);
	data = ("classTree=" + encodeURIComponent(data));
	$.ajax({
		url:collection_servlet,
		async : false,
		data : data,
		dataType : "json",
		type : "post",
		beforeSend:function(){
			$(container).addClass("loading2");
		},
		success : function(result) {
			$(container).removeClass("loading2");
			var tree = eval("("+decodeURIComponent(result["tree"])+")");
			var treeDiv = $("<div class='tree'></div>");
			$(container).append(treeDiv);
					
			var topName = "All";
			if(displayLang=="zh"){
				topName = "全部";
			}
			$(treeDiv).jstree({
					"json_data":{
							"data" : [{"data":topName,
									"state":"open",
									"attr":{"id":"-1"},
									"children": tree}]
						},
						"themes":{"theme":"classic","dots":true,"icons":false},
						"plugins" : ["themes", "json_data","checkbox", "ui" ]
			 });
		}
     });
}

function valueClassConstraint(box,dmtype,dmid,inverse){
	box.addClass("inited");
	dmtype = parseInt(dmtype);
	dmid = parseInt(dmid);
	inverse = parseInt(inverse);
	
	var status = "undownloaded";
	var loading = $("<div class='loading2'></div>");
	box.append(loading);
	fetchClassesInValueClassFilters(box,displayLang, dmtype,
				dmid, inverse, status);
} 

function valueEqualConstraint(box,dmtype,dmid,inverse){
	box.addClass("inited");
	dmtype = parseInt(dmtype);
	dmid = parseInt(dmid);
	inverse = parseInt(inverse);
	var pvalue = $("<ul class='pvalue'></ul>");
	box.append(pvalue);
	
	var status = "undownloaded";
	var loading = $("<div class='loading2'></div>");
	box.append(loading);
	fetchValuesInEqualFilters(displayLang, pvalue, dmtype,
				dmid, inverse,status);
} 

function fetchClassesInValueClassFilters(container,displayLang, dmtype,dmid, inverse, status){
	var array = getCurrentMembers();
	var data = {};
	data["dmtype"] = dmtype;
	data["dmid"] = dmid;
	data["inverse"] = inverse;
	data["members"] = array;
	data["lang"] = displayLang;
	// which genre the eid belongs to
	data["status"] = status;
	data = JSON.stringify(data);
	data = ("cviewDMValueClass=" + encodeURIComponent(data));
	$.ajax({
		url:collection_servlet,
		async : false,
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
			container.find(".loading2").remove();
			handleClassesInInValueClassFilters(result,container,displayLang);
		}
     });	
}

function fetchValuesInEqualFilters(displayLang,container,dmtype,dmid,inverse,status){
	var array = getCurrentMembers();
	var data = {};
	data["dmtype"] = dmtype;
	data["dmid"] = dmid;
	data["inverse"] = inverse;
	data["members"] = array;
	data["lang"] = displayLang;
	// which genre the eid belongs to
	data["status"] = status;
	data = JSON.stringify(data);
	data = ("cviewDMValue=" + encodeURIComponent(data));
	$.ajax({
		url:collection_servlet,
		async : false,
		data : data,
		dataType : "json",
		type : "post",
		success : function(result) {
			handleValuesInInEqualFilters(result,container,displayLang);

			var status = result["status"];
			if (status != "stop") {
				setTimeout(function() {
					fetchValuesInEqualFilters(displayLang,container, dmtype, dmid, inverse, status);
						}, 300);
			} else {
				container.parent().find(".loading2").remove();
			}
		}
     });
}

function handleClassesInInValueClassFilters(result,container,displayLang){
	var tree = eval("("+decodeURIComponent(result["tree"])+")");
	var treeDiv = $("<div class='tree'></div>");
	$(container).append(treeDiv);
			
	var topName = "All";
	if(displayLang=="zh"){
		topName = "全部";
	}
	$(treeDiv).jstree({
			"json_data":{
					"data" : [{"data":topName,
							"state":"open",
							"attr":{"id":"-1"},
							"children": tree}]
				},
				"themes":{"theme":"classic","dots":true,"icons":false},
				"plugins" : ["themes", "json_data","checkbox", "ui" ]
	});
}

function handleValuesInInEqualFilters(result,container,displayLang){
	var values = result["values"];
	var hideLi = false;
	for (i = 0; i < values.length; i++) {
		var item = values[i];
		var etype = item["etype"];
		var eid = item["eid"];
		var euri = item["euri"];
		var literalLang = item["literalLang"];
		var literalType =item["literalType"];
		var memType = item["memberType"];
		var memID = item["memberID"];
		var memLabel = item["memberLabel"];
		
		if ($(container).find("li[etype=" + etype + "][eid=" + eid + "]").length > 0){
			continue;
		}
		
		var li = $("<li></li>");
		$(container).append(li);
		li.attr("etype", etype);
		li.attr("eid", eid);
		var valueLabel = item["valueLabel"];
		if (etype == "l") {
			var equalCheckBox = $("<input type='checkbox' class='equalChkbox' />").prependTo(li);
			var spanLabel = $("<span class='label'></span>").html(valueLabel);
			var hiddenType = $("<input type='hidden' class='literalType' />");
			var hiddenLang = $("<input type='hidden' class='literalLang' />");
			hiddenType.val(literalType);
			hiddenLang.val(literalLang);
			li.append(spanLabel);
			li.append(hiddenType);
			li.append(hiddenLang);
		} else {
			var equalCheckBox = $("<input type='checkbox' class='equalChkbox' />").appendTo(li);
			if(item.directuri==1){
				var alink = $("<a class='vlink' target='_blank'></a>");
				alink.addClass("directlink");
				alink.text(euri);
				alink.attr("href", euri);
				alink.attr("title", euri);
				li.append(alink);
			}else if(item.directlabel==1){
				li.text(valueLabel);
			}else if(item.isimage==1){
				var img = $("<img/>");
				img.attr("src",euri);
				if(displayLang=="en"){
					img.attr("Loading Image");
				}else if(displayLang=="zh"){
					img.attr("加载图片");
				}
				li.append(img);
			}
			else{
				var alink = $("<a class='vlink' target='_blank'></a>");
				alink.text(valueLabel);
				alink.attr("href", getEntityLinkHref(etype, eid,displayLang));
				alink.attr("title", euri);
				li.append(alink);
				
				//对于uri，异步取label
				var needLabel = item["needLabel"];
				if(needLabel){
					fetchLabel(alink,eid,displayLang);
				}
			}
		}
	}
}

/*end: filter value constraint*/


